/**
 * SpringMVC restful 风格
 * 订单管理控制器，控制关于订单的一些业务逻辑操作
 * @author yanwl
 * @date 2014-10-08
 */
package com.chnbst.bstyun.controller.user;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chnbst.bstyun.core.common.Pager;
import com.chnbst.bstyun.core.common.SignUtil;
import com.chnbst.bstyun.model.pojo.Goods;
import com.chnbst.bstyun.model.pojo.GoodsRelation;
import com.chnbst.bstyun.model.pojo.Order;
import com.chnbst.bstyun.model.pojo.Payment;
import com.chnbst.bstyun.model.pojo.User;
import com.chnbst.bstyun.model.vo.OrderVo;
import com.chnbst.bstyun.service.GoodsRelationService;
import com.chnbst.bstyun.service.GoodsService;
import com.chnbst.bstyun.service.OrderService;
import com.chnbst.bstyun.service.PaymentService;
import com.chnbst.bstyun.service.UserService;
import com.chnbst.bstyun.service.VoucherService;

@Controller
@RequestMapping("/consume/order")
public class OrderController {
	/**
	 * 每页显示的订单条数
	 */
	private int orderPageSize = 5;
	private static final String ROLE_COMPANY = "ROLE_COMPANY";//公司用户
//	private static final String ROLE_PERSON = "ROLE_PERSON";//个人用户
//	private static final String ROLE_AGENT = "ROLE_AGENT";//代理商
	/**
	 * 注入业务逻辑层
	 */
	@Autowired
	private OrderService orderService;
	@Autowired
	private UserService userService;
	@Autowired
	private VoucherService voucherService;
	@Autowired
	private PaymentService paymentService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private GoodsRelationService goodsRelationService;
	
	/**
	 * ajax请求 查询用户订单信息
	 * @return 订单信息
	 */
	@RequestMapping(value="/queryList",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> selectOrderByUserId(HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
		User user = (User)request.getSession().getAttribute("userInfo");
		map.put("userId", user.getUserId());
		map.put("isYun", user.getIsYun());
		List<OrderVo> orderList = orderService.selectOrderByUserId(map);
		map.put("orderList", orderList);
		return map;
	}
	
	
	/**
	 * http://xxx.com/consume/order/manage
	 * get请求 查询用户订单信息
	 * @return 订单信息
	 */
	@RequestMapping(value="/manage",method=RequestMethod.GET)
	public ModelAndView manage(HttpServletRequest request){
		ModelAndView mav = new ModelAndView();
		List<Goods> goodsList = goodsService.selectAllGoods(new HashMap<String, Object>());
		mav.addObject("goodsList", goodsList);
		mav.setViewName("users/consume_record/order_manage/order-list");
		return mav;
	}
	
	
	/**
	 * ajax请求 查询多条件查询用户订单信息
	 * @return 订单信息
	 */
	@RequestMapping(value="/search",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> search(String startTime,String endTime,String goodsId,String orderState,HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
		User user = (User)request.getSession().getAttribute("userInfo");
		map.put("userId", user.getUserId());
		map.put("isYun", user.getIsYun());
		if(SignUtil.isEmpty(goodsId)) {
			goodsId = null;
		}
		if(SignUtil.isEmpty(orderState)) {
			orderState = null;
		}
		if(SignUtil.isEmpty(startTime)) {
			startTime = null;
		}
		if(SignUtil.isEmpty(endTime)) {
			endTime = null;
		}
		map.put("orderState", orderState);
		map.put("goodsId", goodsId);
		map.put("startTime", startTime);
		map.put("endTime", endTime);
		
		int totalRows = orderService.selectOrderVoCountByConditions(map);
		
		String pg = request.getParameter("page");
		int currPage = 1;
		if(SignUtil.isNotEmpty(pg)) {
			currPage = Integer.valueOf(pg);
		}
		
		int pageCount = Pager.getPageCount(totalRows, orderPageSize);
		if(pageCount < currPage) {
			currPage = pageCount;
		}
		int start = Pager.getStart(currPage, orderPageSize);
		
		map.put("start", start);
		map.put("pageSize", orderPageSize);
		map.put("sortField", "t.order_id");
		map.put("sortOrder", "desc");
		
		
		List<OrderVo> orderList = orderService.selectOrderByConditions(map);
		map.put("orderList", orderList);
		map.put("page", currPage);
		map.put("pageCount", pageCount);
		map.put("totalRows", totalRows);
		return map;
	}
	
	/**
	 * ajax请求 查询已删除的订单信息
	 * @return 订单信息
	 */
	@RequestMapping(value="/searchDeleteOrder",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> searchDeleteOrder(HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
		User user = (User)request.getSession().getAttribute("userInfo");
		map.put("userId", user.getUserId());
		
		int totalRows = orderService.selectDeleteOrderVoCountByMap(map);
		
		String pg = request.getParameter("page");
		int currPage = 1;
		if(SignUtil.isNotEmpty(pg)) {
			currPage = Integer.valueOf(pg);
		}
		
		int pageCount = Pager.getPageCount(totalRows, orderPageSize);
		if(pageCount < currPage) {
			currPage = pageCount;
		}
		int start = Pager.getStart(currPage, orderPageSize);
		
		map.put("start", start);
		map.put("pageSize", orderPageSize);
		map.put("sortField", "t.order_id");
		map.put("sortOrder", "desc");
		
		List<OrderVo> orderList = orderService.selectDeleteOrderVoByMap(map);
		map.put("orderList", orderList);
		map.put("page", currPage);
		map.put("pageCount", pageCount);
		map.put("totalRows", totalRows);
		return map;
	}
	
	/**
	 * http://xxx.com/consume/order/order_detail
	 * get请求 查询用户订单详情(待做)
	 * @return 订单详情
	 */
	@RequestMapping(value="/order_detail",method=RequestMethod.GET)
	public ModelAndView order_detail(HttpServletRequest request){
		ModelAndView mav = new ModelAndView();
		
		Integer orderId = Integer.valueOf(request.getParameter("orderId"));
		OrderVo orderVo = orderService.selectOrderVoByOrderId(orderId);
		
		List<GoodsRelation> list = goodsRelationService.selectByGoodsId(orderVo.getGoodsId());
		
		String products = "";
		for (int i = 0; i < list.size(); i++) {
			products += list.get(i).getProductName()+"*1";
			if(i < list.size()-1) {
				products += "+";
			}
		}
		orderVo.setProIds(products);//商品包含的产品组合
		
		if(orderVo.getPayMoney() == null) {
			orderVo.setPayMoney(0.00);
		}
		
		if(SignUtil.isEmpty(orderVo.getVoucherMoney())) {
			orderVo.setVoucherMoney("0.00");
		}
		mav.addObject("orderVo", orderVo);
		mav.setViewName("users/consume_record/order_manage/order-detail");
		return mav;
	}
	
	/**
	 * ajax请求 删除订单信息
	 * @return 订单信息
	 */
	@RequestMapping(value="/deleteOrder",method=RequestMethod.POST)
	@ResponseBody
	public boolean deleteOrder(String orderIds,Integer deleteState,HttpServletRequest request){
		User user = (User)request.getSession().getAttribute("userInfo");
		boolean isSuccess = true;
		if(deleteState == 2) {
			deleteState = null;
		}
		if(orderIds.contains(",")) {
			String[] ids = orderIds.split(",");
			for (String str : ids) {
				Order order = orderService.selectOrderByOrderId(Integer.valueOf(str));
				if(!"0".equals(order.getOrderState())) {
					if(user.getRoleId().equals(ROLE_COMPANY)) {
						if(order.getParentId() == user.getUserId()) {
							order.setIsDelete(deleteState);
							isSuccess = orderService.updateOrderByOrderId(order);
						}
					}else {
						order.setIsDelete(deleteState);
						isSuccess = orderService.updateOrderByOrderId(order);
					}
				}
				
			}
		}else {
			Order order = orderService.selectOrderByOrderId(Integer.valueOf(orderIds));
			if(!"0".equals(order.getOrderState())) {
				if(user.getRoleId().equals(ROLE_COMPANY)) {
					if(order.getParentId() == user.getUserId()) {
						order.setIsDelete(deleteState);
						isSuccess = orderService.updateOrderByOrderId(order);
					}
				}else {
					order.setIsDelete(deleteState);
					isSuccess = orderService.updateOrderByOrderId(order);
				}
			}
		}
		return isSuccess;
	}
	
	
	/**
	 * ajax请求 作废订单信息
	 * @return 订单信息
	 */
	@RequestMapping(value="/closeOrder",method=RequestMethod.POST)
	@ResponseBody
	public boolean closeOrder(String orderId,HttpServletRequest request){
		boolean isSuccess = false;
		Integer oId = Integer.valueOf(orderId);
		Order order = orderService.selectOrderByOrderId(oId);
		if(order.getNewProId() == null) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("orderState", 0);
			map.put("userId", order.getUserId());
			List<Order> orders = orderService.selectOrdersByMap(map);
			if(orders.size() <= 0) {
				User user = userService.selectUserInfoByUserId(order.getUserId());
				user.setUserValid("1");
				userService.updateUserByKey(user);
			}
		}
		Payment payment = paymentService.selectPaymentByOrderId(oId);
		if(payment != null) {
			payment.setIsCancel(1);
			paymentService.updatePayment(payment);
		}
		order.setOrderState(2);
		isSuccess = orderService.updateOrderByOrderId(order);
		return isSuccess;
	}
	
	/**
	 * ajax请求 检测订单是否是线下支付
	 * @return boolean
	 */
	@RequestMapping(value="/checkOrderIsPayment",method=RequestMethod.POST)
	@ResponseBody
	public boolean checkOrderIsPayment(String orderId,HttpServletRequest request){
		boolean isSuccess = false;
		Integer oId = Integer.valueOf(orderId);
		Payment payment = paymentService.selectPaymentByOrderId(oId);
		if(payment != null) {
			isSuccess = true;
		}
		return isSuccess;
	}
}
